package cn.easier.activity.console.controller;

import cn.easier.activity.console.entity.ActivityConsoleRole;
import cn.easier.activity.console.entity.ActivityConsoleUser;
import cn.easier.activity.console.entity.UserParams;
import cn.easier.activity.console.repository.ActivityConsoleUserRepository;
import cn.easier.activity.console.repository.ActivityConsoleRoleRepository;
import cn.easier.activity.console.service.ActivityConsoleUserService;
import cn.easier.activity.console.utils.FileUtil;
import cn.easier.club.base.dto.ResultInfo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * 后台用户Controller
 */
@Controller
@RequestMapping("/activity/console-user")
public class ActivityConsoleUserController {

    /**
     * 文件根路径
     */
    @Value("${metadata.configuration.static-resource-path}")
    public String realPath;
    /**
     * 用户图片
     */
    @Value("${metadata.activity-platform.activity-console-user.image-path}")
    public String activityConsoleUserImagePath;

    Logger logger = LoggerFactory.getLogger(ActivityConsoleUserController.class);

    @Autowired
    ActivityConsoleUserService activityConsoleUserService;

    private final ActivityConsoleUserRepository activityConsoleUserRepository;
    private final ActivityConsoleRoleRepository activityConsoleRoleRepository;

    public ActivityConsoleUserController(ActivityConsoleUserRepository activityConsoleUserRepository, ActivityConsoleRoleRepository activityConsoleRoleRepository) {
        this.activityConsoleUserRepository = activityConsoleUserRepository;
        this.activityConsoleRoleRepository = activityConsoleRoleRepository;
    }

    /**
     * 退出登陆
     * @return
     */
    @GetMapping("/login-out")
    public String loginOut() {
        System.out.println("退出登陆");
        return "退出登陆";
    }

    /**
     * 创建用户
     * theSwordOfDamocles
     *
     * @param userParams 用户
     * @return
     */
    @PostMapping("/createUser")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ROLE_USER_SUPERADMIN','ROLE_USER_ADMIN')")
    public ResultInfo register(@RequestBody UserParams userParams) {
        //PreAuthorize 已经判断权限 在调用另一个方法 在判断一次权限是否对  只为了求稳
        ActivityConsoleUser name = this.getPrincipal();
        String user = name.getAuthoritiesStr();
        if (!"ROLE_USER_SUPERADMIN".equals(user) && !"ROLE_USER_ADMIN".equals(user)) {
            logger.info("有人试图注册用户，user：=>{}", name.getUsername());
            return new ResultInfo("ERROR", "有人非法注册用户", null);
        }
        List<ActivityConsoleUser> byUsername = activityConsoleUserRepository.findByUsername(userParams.getUsername());
        if (CollectionUtils.isNotEmpty(byUsername)) {
            return new ResultInfo("ERROR", "该用户名已经被注册", null);
        }
        List<ActivityConsoleUser> byPhoneNum = activityConsoleUserRepository.findByPhoneNum(userParams.getPhoneNum());
        if (CollectionUtils.isNotEmpty(byPhoneNum)) {
            return new ResultInfo("ERROR", "该手机号已经被注册", null);
        }
        if ("ROLE_USER_ADMIN".equals(user)){
            if (userParams.getAuthoritiesStr().equals("USER_ADMIN")){
                return new ResultInfo("ERROR", "对不起,您只能授权普通用户", null);
            }
        }
        ResultInfo resultInfo = activityConsoleUserService.saveMessage(userParams);
        return resultInfo;
    }

    /**
     * 修改用户是否禁用状态
     * theSwordOfDamocles
     *
     * @return
     */
    @PostMapping("/changeEnabled")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ROLE_USER_SUPERADMIN','ROLE_USER_ADMIN')")
    public ResultInfo changeEnabled(@RequestParam(value = "uid", required = true) Integer uid, @RequestParam(value = "enabled", required = true) boolean enabled) {
        //PreAuthorize 已经判断权限 在调用另一个方法 在判断一次权限是否对  只为了求稳
        ActivityConsoleUser name = this.getPrincipal();
        String user = name.getAuthoritiesStr();
        if (!"ROLE_USER_SUPERADMIN".equals(user) && !"ROLE_USER_ADMIN".equals(user)) {
            logger.info("有人试图禁用用户，user：=>{}", name.getUsername());
            return new ResultInfo("ERROR", "有人非法改变用户状态", null);
        }
        if ("ROLE_USER_ADMIN".equals(user)){
            ActivityConsoleUser byUid = activityConsoleUserRepository.findByUid(Long.valueOf(uid));
            if (byUid.getAuthoritiesStr().equals("ROLE_USER_SUPERADMIN") || byUid.getAuthoritiesStr().equals("ROLE_USER_ADMIN")){
                return new ResultInfo("ERROR", "对不起,您只能操作普通用户", null);
            }
        }
        ResultInfo resultInfo = activityConsoleUserService.changeEnabled(uid, enabled);
        return resultInfo;
    }


    /**
     * 查看用户列表
     * theSwordOfDamocles
     * @return
     */
    @RequestMapping(value = "/getUserMessage", method = RequestMethod.GET)
    @ResponseBody
    @PreAuthorize("hasAnyRole('ROLE_USER_SUPERADMIN','ROLE_USER_ADMIN')")
    public ResultInfo getUserMessage(@RequestParam(value = "pageNum", required = true) int pageNum,
                                     @RequestParam(value = "pageSize", required = true) int pageSize,
                                     @RequestParam(value = "userName", required = false) String userName) {
        List<Object> result = activityConsoleUserService.getUserMessage(pageNum, pageSize,userName);
        Object o = result.get(result.size() - 1);
        result.remove(result.size() - 1);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), String.valueOf(o), result);
    }

    /**
     * 查看所有权限
     * theSwordOfDamocles
     *
     * @return
     */
    @PostMapping("/getAuthoritiesStr")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ROLE_USER_SUPERADMIN','ROLE_USER_ADMIN')")
    public ResultInfo getAuthoritiesStr() {
        //PreAuthorize 已经判断权限 在调用另一个方法 在判断一次权限是否对  只为了求稳
        ActivityConsoleUser name = this.getPrincipal();
        String user = name.getAuthoritiesStr();
        if (!"ROLE_USER_SUPERADMIN".equals(user)) {
            logger.info("有人试图查看权限，user：=>{}", name.getUsername());
            return new ResultInfo("ERROR", "有人非法查看所有权限", null);
        }
        List<ActivityConsoleRole> all = activityConsoleRoleRepository.findAll();
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", all);
    }

    /**
     * 更新用户
     *
     * @param userParams
     * @return
     */
    @PostMapping("/updateUser")
    @ResponseBody
    @PreAuthorize("hasAnyRole('ROLE_USER_SUPERADMIN','ROLE_USER_ADMIN')")
    public ResultInfo updateUser(@RequestBody UserParams userParams) {
        ActivityConsoleUser name = this.getPrincipal();
        String user = name.getAuthoritiesStr();
        if (!"ROLE_USER_SUPERADMIN".equals(user) && !"ROLE_USER_ADMIN".equals(user)) {
            logger.info("有人试图修改别人信息，user：=>{}", name.getUsername());
            return new ResultInfo("ERROR", "有人试图修改别人信息", null);
        }
        if ("ROLE_USER_ADMIN".equals(user)){
            if (userParams.getAuthoritiesStr().equals("USER_ADMIN")){
                return new ResultInfo("ERROR", "对不起,您只能授权普通用户", null);
            }
        }
        try {
            ResultInfo resultInfo = activityConsoleUserService.updateUser(userParams);
            logger.info("修改用户成功: =>{}", resultInfo);
            return resultInfo;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改用户异常,activityConsoleUser: =>{}", userParams);
            return  new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "更新用户异常", null);
        }
    }

    private String uploadFile(MultipartFile imageFile) {
        String path = (realPath + activityConsoleUserImagePath).replace("/", File.separator);
        String imageFileName = FileUtil.doFile(imageFile, path, "user_image_");
        //静态资源映射 + 文件地址 + 上传文件名称
        return activityConsoleUserImagePath + imageFileName;
    }
    @RequestMapping(value = "/getPrincipal", method = RequestMethod.GET)
    @ResponseBody
    public ResultInfo principal() {
        ActivityConsoleUser principal = this.getPrincipal();
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", principal);
    }

    /*
     *PostAuthorize 已经支持EL 表达式
     * 通过安全框架获得 登录的用户信息
     */
    private ActivityConsoleUser getPrincipal() {
        Object pricipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ActivityConsoleUser activityConsoleUser;
        if(pricipal instanceof ActivityConsoleUser){
            activityConsoleUser = (ActivityConsoleUser) pricipal;
        } else {
            activityConsoleUser = null;
        }
        return activityConsoleUser;
    }
}
